package com.tiyende.kash.loop.ui.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.os.Build
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.text.style.TypefaceSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.TiyendeApp
import com.tiyende.kash.loop.common.CommonFragment
import com.tiyende.kash.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.kash.loop.configs.TiyendeConfigs
import com.tiyende.kash.loop.databinding.TiyendeFragmentAuthenticationStepCommonBinding
import com.tiyende.kash.loop.event.TiyendeEventData
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.ui.activity.TiyendeAuthenticationStepsActivity
import com.tiyende.kash.loop.ui.activity.TiyendePickCityActivity
import com.tiyende.kash.loop.ui.adapter.TiyendeAuthenticationStepCommonAdapter
import com.tiyende.kash.loop.ui.dialog.TiyendeBankComfirmDialog
import com.tiyende.kash.loop.ui.dialog.TiyendeChooseDialog
import com.tiyende.kash.loop.ui.dialog.TiyendeGenderDialog
import com.tiyende.kash.loop.ui.popupwindow.TiyendeCommonPopupwindow
import com.tiyende.kash.loop.utils.TiyendeAssetsJsonReader
import com.tiyende.kash.loop.utils.TiyendeDensityUtil
import com.tiyende.kash.loop.utils.decoration.LinearSpacingItemDecoration
import com.tiyende.kash.loop.utils.helper.TiyendeProcessHelper
import com.tiyende.kash.loop.utils.log.TiyendeLogger
import com.tiyende.kash.loop.utils.track.TrackPointManager
import com.tiyende.kash.loop.weight.pickerview.builder.TimePickerBuilder
import com.tiyende.kash.loop.weight.pickerview.listener.OnTimeSelectListener
import com.tiyende.kash.loop.weight.pickerview.view.TimePickerView
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/19 14:19
 * @Annotation：认证流程 - 通用
 */
class TiyendeAuthenticationStepCommonFragment(): CommonFragment() {
    // 使用可空类型的 backing property
    private var _binding: TiyendeFragmentAuthenticationStepCommonBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var stepItem: JSONObject? = null
    private var stepTitle = ""

    private var generalAdapter: TiyendeAuthenticationStepCommonAdapter? = null
    private var mSelectPosition = -1

    //出生日期选择
    private var pvStartDateView: TimePickerView? = null
    var startTime = 0L

    constructor(data: JSONObject): this(){
        this.stepItem = data
        stepTitle = data.optString("stepTitle")
    }

    override fun getTiyendeRootView(inflater: LayoutInflater): View {
        _binding = TiyendeFragmentAuthenticationStepCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initTiyendeView() {
        rootViewBinding.rootLayout.setBackgroundColor("#00000000".toColorInt())
        initAuthStepListView()

        //提交按钮移到外层，通过通知的方式控制提交
        _binding?.authStepCommonNext?.visibility = View.INVISIBLE
    }

    override fun initTiyendeListener() {
        //下一步
        _binding?.authStepCommonNext?.setOnClickListener {
            onTiyendeSubmitAuthenticationInfoAction()
        }
    }

    override fun loadTiyendeData() {
        val dataList = arrayListOf<JSONObject>()
        if (stepItem != null){
            addEventPointRequestAction(String.format(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_XX_START,stepTitle))

            _binding?.holderNameLayout?.visibility = View.GONE
            _binding?.authStepPersonalInfoTipsLayout?.visibility = View.GONE
            when(stepTitle){
                "personal_info" -> {
                    _binding?.imgAuthStepTipsIcon?.setImageResource(R.mipmap.tiyende_activity_authentication_steps_personal_info_tips_icon)
                    val showKey1 = getString(R.string.tiyende_authentication_step_personal_info_tips_key1)
                    val showKey2 = getString(R.string.tiyende_authentication_step_personal_info_tips_key2)
                    val showText = String.format(getString(R.string.tiyende_authentication_step_personal_info_tips),showKey1,showKey2)
                    val startIndex1 = showText.indexOf(showKey1)
                    val startIndex2 = showText.indexOf(showKey2)
                    val dataSecuritySpannable = SpannableString(showText)
                    dataSecuritySpannable.setSpan(ForegroundColorSpan("#FF3ED9AB".toColorInt()), startIndex1, startIndex1 + showKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                    dataSecuritySpannable.setSpan(ForegroundColorSpan("#FF3ED9AB".toColorInt()), startIndex2, startIndex2 + showKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { // TypefaceSpan(Typeface) added in API 28
                        dataSecuritySpannable.setSpan(TypefaceSpan(TiyendeApp.app.getBoldTypeface()), startIndex1, startIndex1 + showKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                        dataSecuritySpannable.setSpan(TypefaceSpan(TiyendeApp.app.getBoldTypeface()), startIndex2, startIndex2 + showKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                    } else {
                        dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex1, startIndex1 + showKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                        dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex2, startIndex2 + showKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                    }
                    _binding?.textAuthStepPersonalInfoTips?.text = dataSecuritySpannable
                    _binding?.authStepPersonalInfoTipsLayout?.visibility = View.VISIBLE
                }
                "account_info" -> {
                    var fullName = ""
                    //从流程数据里获取全名
                    val processData = TiyendeProcessHelper.queryTiyendeAuthenticationData()
                    processData?.let { data ->
                        fullName = data.optString("fullName")
                    }
                    _binding?.holderNameLayout?.visibility = View.VISIBLE
                    _binding?.textFullName?.text = fullName

                    _binding?.imgAuthStepTipsIcon?.setImageResource(R.mipmap.tiyende_activity_authentication_steps_account_info_icon)
                    _binding?.textAuthStepPersonalInfoTips?.text = getString(R.string.tiyende_authentication_step_account_info_tips)
                    _binding?.authStepPersonalInfoTipsLayout?.visibility = View.VISIBLE
                }
            }

            val dataArray = stepItem?.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..<dataArray.length()){
                    val item = dataArray.optJSONObject(i)
                    item.put("stepTitle",stepTitle)
                    item.put("isShowStepItem",true)
                    dataList.add(item)
                }
            }
        }
        generalAdapter?.data = dataList
    }

    /**
     * 初始化Views
     */
    private fun initAuthStepListView(){
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.authStepCommonListView?.layoutManager = layoutManager
        val topDecoration = TiyendeDensityUtil.dp2px(16f)
        _binding?.authStepCommonListView?.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        generalAdapter = TiyendeAuthenticationStepCommonAdapter(_binding?.authStepCommonListView)
        _binding?.authStepCommonListView?.adapter = generalAdapter
        _binding?.authStepCommonListView?.itemAnimator = DefaultItemAnimator()
        generalAdapter?.setOnItemChildClickListener { _, childView, position ->
            _binding?.root?.clearFocus()
            mSelectPosition = position
            val item = generalAdapter?.getItem(position)
            item?.let {
                when (it.optString("action")) {
                    "DATE_PICK" -> {//时间选择
                        showTiyendeBirthdayDialog()
                    }
                    "GENDER_PICK" -> {//性别选择
                        val dataList = arrayListOf<JSONObject>()
                        val dataArray = it.optJSONArray("values")
                        if (dataArray != null) {
                            for (i in 0..<dataArray.length()) {
                                dataList.add(dataArray.optJSONObject(i))
                            }
                        }
                        showTiyendeGenderDialog(dataList)
                    }
                    "RESIDENCE_TYPE" -> {//住宅性质选择
                        val dataList = TiyendeAssetsJsonReader.readResidentTypeListFromAssets()
                        showTiyendeChooseDialog(dataList)
                    }
                    "SELECT_CITY" -> {//城市选择
                        showTiyendePickCityLauncher()
                    }
                    "INDUSTRY_TYPE" -> {//行业类型
                        val dataList = TiyendeAssetsJsonReader.readIndustryTypeListFromAssets()
                        showTiyendeChooseDialog(dataList)
                    }
                    "SELECT" -> {//选择
                        val dataList = arrayListOf<JSONObject>()
                        val dataArray = it.optJSONArray("values")
                        if (dataArray != null) {
                            for (i in 0..<dataArray.length()) {
                                dataList.add(dataArray.optJSONObject(i))
                            }
                        }
                        showSelectPopupwindow(childView, dataList)
                    }
                }
            }
        }
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        val selectPopup = TiyendeCommonPopupwindow(requireContext())
        selectPopup.setWindowWidth(view.width + TiyendeDensityUtil.dp2px(10f))
        selectPopup.setSelectItemListener(object : TiyendeCommonPopupwindow.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                generalAdapter?.let {
                    val item = it.getItem(mSelectPosition)
                    item.put("selectItem",data)
                    it.notifyItemChanged(mSelectPosition)

                    if (data != null){
                        val subRemark = "${data.optString("value")}$$${data.optString("duration")}"
                        addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                    }
                }
            }
            //关闭监听
            override fun onDismissListener() {
            }
        })
        _binding?.root?.let {
            selectPopup.show(view, it)
            selectPopup.setBrandList(dataList)
        }
    }

    private fun showTiyendeBirthdayDialog(){
        //开始选择时间
        startTime = System.currentTimeMillis()
        if(pvStartDateView == null){
            //时间可选范围18-100岁
            //当前日期
            val curtDate = Calendar.getInstance()
            val startDate = Calendar.getInstance()
            startDate.timeInMillis = curtDate.timeInMillis
            startDate.add(Calendar.YEAR,-100)

            val endDate = Calendar.getInstance()
            endDate.timeInMillis = curtDate.timeInMillis
            endDate.add(Calendar.YEAR,-18)

            pvStartDateView = TimePickerBuilder(requireContext(), object : OnTimeSelectListener {
                override fun onTimeSelect(date: Date?, v: View?) {
                }

                @SuppressLint("SimpleDateFormat")
                override fun onTimeSelectString(date: Date?, showDate: String?) {
                    val value = SimpleDateFormat("yyyy-MM-dd").format(date)
                    //可根据需要自行截取数据显示
                    val item = generalAdapter?.getItem(mSelectPosition)
                    item?.let {
                        val obj = JSONObject()
                        obj.put("title",showDate)
                        obj.put("title_sw",showDate)
                        obj.put("value",value)
                        it.put("selectItem",obj)

                        generalAdapter?.notifyItemChanged(mSelectPosition)

                        val subRemark = "${value}$$${System.currentTimeMillis() - startTime}"
                        addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                    }
                }
            })
                .setDate(endDate) //默认选中
                .setRangDate(startDate, endDate) //可选择时间范围
                .setLayoutRes(R.layout.tiyende_dialog_birthday) { v ->
//                    val ivClose = v?.findViewById<ImageView>(R.id.ivClose)
//                    ivClose.setOnClickListener {
//                        pvStartDateView?.dismiss()
//                    }
                    //确定
                    val btnDone = v.findViewById<TextView>(R.id.btnDone)
                    btnDone.setOnClickListener {
                        pvStartDateView?.returnData()
                        pvStartDateView?.dismiss()
                    }
                }
                .isDialog(true)
                .setContentTextSize(20)
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .setLabel("", "", "", "", "", "")
                .setLineSpacingMultiplier(3.5f)
                .setTextXOffset(65, 65, 65, 65, 65, 65)
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTextColorCenter("#FF3ED9AB".toColorInt()) //设置选中项文字颜色
                .setTextColorOut("#FFCBD5E1".toColorInt())//默认颜色
                .setBgColor("#00000000".toColorInt())
                .isAlphaGradient(true)
                .setItemVisibleCount(5)
                .isCyclic(true)
                .setDividerColor(ContextCompat.getColor(requireContext(), R.color.transparent))
                .build()
            val dialog = pvStartDateView?.dialog
            if (dialog != null){
                val dialogWindow = dialog.window
                if (dialogWindow != null) {
                    val params = dialogWindow.attributes
                    params.width = WindowManager.LayoutParams.MATCH_PARENT
                    params.height = WindowManager.LayoutParams.WRAP_CONTENT
                    dialogWindow.attributes = params
                    dialogWindow.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
                    dialogWindow.setGravity(Gravity.BOTTOM)
                    dialogWindow.setDimAmount(0.3f)
                }
            }
        }
        pvStartDateView?.show()
    }

    /**
     * 选择性别
     */
    private fun showTiyendeGenderDialog(genderList: ArrayList<JSONObject>){
        val genderDialog = TiyendeGenderDialog(requireContext(),object : TiyendeGenderDialog.IDialogCallback{
            override fun onGenderSelectedItem(data: JSONObject) {
                val item = generalAdapter?.getItem(mSelectPosition)
                item?.put("selectItem",data)
                generalAdapter?.notifyItemChanged(mSelectPosition)
                val subRemark = "${data.optString("value")}$$${data.optString("duration")}"
                addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT,item?.optString("paramName")),subRemark)
            }
        })
        genderDialog.show()
        genderDialog.addTiyendeGenderList(genderList)
    }

    /**
     * 选择城市
     */
    private fun showTiyendePickCityLauncher(){
        val item = generalAdapter?.getItem(mSelectPosition)
        item?.let {
            startTime = System.currentTimeMillis()

            val intent = Intent(context, TiyendePickCityActivity::class.java)
            intent.putExtra("pageName", it.optString("title").replace("*",""))
            startOpenPickCityResultLauncher.launch(intent)
        }
    }

    /**
     * 选择Dialog
     */
    private fun showTiyendeChooseDialog(dataList: ArrayList<String>){
        startTime = System.currentTimeMillis()
        val item = generalAdapter?.getItem(mSelectPosition)
        item?.let {
            val paramName = "${stepTitle}_${it.optString("paramName")}"
            val chooseDialog = TiyendeChooseDialog(requireContext(), paramName,object : TiyendeChooseDialog.IDialogCallback{
                override fun onTiyendeSelectedItem(cityName: String) {
                    //可根据需要自行截取数据显示
                    val obj = JSONObject()
                    obj.put("title",cityName)
                    obj.put("title_sw",cityName)
                    obj.put("value",cityName)
                    it.put("selectItem",obj)

                    generalAdapter?.notifyItemChanged(mSelectPosition)

                    val subRemark = "${cityName}$$${System.currentTimeMillis() - startTime}"
                    addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT,paramName),subRemark)
                }
            })
            chooseDialog.setCancelable(true)
            chooseDialog.setCanceledOnTouchOutside(true)
            chooseDialog.show()
            chooseDialog.addTiyendeTitleText(it.optString("hint"))
            chooseDialog.addTiyendeDataList(dataList)
        }
    }

    /**
     * 填写银行账户信息确认dialog
     */
    private fun showTiyendeBankAccountDialog(params: JSONObject){
        val confirmDialog = TiyendeBankComfirmDialog(requireContext(),stepTitle,object: TiyendeBankComfirmDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btAllCorrect){
                    val act = getAct() as TiyendeAuthenticationStepsActivity
                    act.onAuthenticationStepSubmitAction(params)
                }
            }
        })
        confirmDialog.setCancelable(true)
        confirmDialog.setCanceledOnTouchOutside(true)
        confirmDialog.show()
        confirmDialog.addTiyendeTitleText(getString(R.string.tiyende_authentication_step_account_info_confirm_tips))
        confirmDialog.addTiyendeBankAccountInfo(params)

    }

    /**
     * 通用类型列表
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowCommonSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        generalAdapter?.let {
            for (i in 0..<it.itemCount){
                val item = it.getItem(i)
                //存在 isMust && isMust == ”NO“  非必填
                if (item.has("isMust") && item.optString("isMust") == "NO"){
                    continue
                }
                //必填 && 没有内容 || 内容为空
                if (!item.has("selectItem")){
                    isAllow = false
                    break
                }
                val selectItem = item.optJSONObject("selectItem")
                if (selectItem == null){
                    isAllow = false
                    break
                }
                if (selectItem.optString("value").isEmpty()){
                    isAllow = false
                    break
                }
            }
        }
        return isAllow
    }

    /**
     * 城市选择
     */
    private val startOpenPickCityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                TiyendeLogger.e(">>>>>>onActivityResult: data = " + result.data)
                result.data?.let { data ->
                    val cityName = data.getStringExtra("pickCityName").toString()

                    val item = generalAdapter?.getItem(mSelectPosition)
                    item?.let {
                        val paramName = "${stepTitle}_${it.optString("paramName")}"
                        //可根据需要自行截取数据显示
                        val obj = JSONObject()
                        obj.put("title",cityName)
                        obj.put("title_sw",cityName)
                        obj.put("value",cityName)
                        it.put("selectItem",obj)

                        generalAdapter?.notifyItemChanged(mSelectPosition)

                        val subRemark = "${cityName}$$${System.currentTimeMillis() - startTime}"
                        addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT,paramName),subRemark)
                    }
                }
            }
        }
    }

    /**
     * 提交进件信息
     */
    private fun onTiyendeSubmitAuthenticationInfoAction(){
        _binding?.root?.clearFocus()
        stepItem?.let {
            addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_NEXT, stepTitle),"")

            if (!isAllowCommonSubmit()){
                showErrorTipsDialog(getString(R.string.tiyende_dialog_tips_submit_error),stepTitle)
                return
            }
            val params = JSONObject().addCommonParams().apply {
                put("path", it.optString("apiUrl").replace("/",""))
            }
            generalAdapter?.let { adapter ->
                for (i in 0..< adapter.itemCount){
                    val item = adapter.getItem(i)
                    if (item.has("selectItem")){
                        val selectItem = item.optJSONObject("selectItem")
                        if (selectItem != null){
                            params.put(item.optString("paramName"),selectItem.optString("value"))
                        }
                    }
                }
            }
            TiyendeLogger.e(">>>>>>submit data >>>>>>>$params")

            // TODO: Step Next 批量埋点上报
            TrackPointManager.getInstance().manualReport()
            //印度添加银行卡信息，需要二次确认dialog
            if (stepTitle == "account_info" && TiyendeConfigs.isIndia()){
                showTiyendeBankAccountDialog(params = params)
            } else {
                val act = getAct() as TiyendeAuthenticationStepsActivity
                act.onAuthenticationStepSubmitAction(params)
            }
        }
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_SUBMIT_AUTHENTICATION -> {
                onTiyendeSubmitAuthenticationInfoAction()
            }
            else -> {

            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        if (stepItem != null){
            addEventPointRequestAction(String.format(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_XX_END,stepTitle))
        }
    }
}